<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-hasPermi="['jihuo:data:add']" icon="el-icon-plus" plain size="mini" type="primary" @click="handleAdd">
          新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPermi="['jihuo:data:edit']" :disabled="single" icon="el-icon-edit" plain size="mini" type="success" @click="handleUpdate">
          修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPermi="['jihuo:data:remove']" :disabled="multiple" icon="el-icon-delete" plain size="mini" type="danger" @click="handleDelete">
          删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPermi="['jihuo:data:upload']" icon="el-icon-upload" plain size="mini" type="warning" @click="handleUpload">
          导入
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPermi="['jihuo:data:export']" icon="el-icon-download" plain size="mini" type="warning" @click="handleExport">
          导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="dataList" @selection-change="handleSelectionChange">
      <el-table-column align="center" type="selection" width="55"/>
      <el-table-column align="center" label="更新时间" prop="jhUpdatedTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.jhUpdatedTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="数据包名称" prop="jhDataName"/>
      <el-table-column align="center" label="数据包数量" prop="jhNum"/>
<!--      <el-table-column align="center" label="删除标志" prop="jhDeleted"/>-->
<!--      <el-table-column align="center" label="货品链接" prop="jhUrl"/>-->
      <el-table-column align="center" label="备注" prop="jhRemark"/>
      <el-table-column align="center" label="解析失败数量">
        <template slot-scope="scope">
          <el-button type="text" @click="showFailUrls(scope.row)">
            {{ scope.row.jhFailUrls ? scope.row.jhFailUrls.length : 0 }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column align="center" label="解析成功数量">
        <template slot-scope="scope">
          <el-button type="text" @click="showSuccessUrls(scope.row)">
            {{ scope.row.jhSuccessUrls ? scope.row.jhSuccessUrls.length : 0 }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column align="center" label="状态" prop="status" width="120">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === 'processing' ? 'warning' : 'success'">
            {{ scope.row.status === 'processing' ? '处理中' : '处理完成' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
        <template slot-scope="scope">
          <el-button v-hasPermi="['jihuo:data:edit']" icon="el-icon-edit" size="mini" type="text" @click="handleUpdate(scope.row)">
            修改
          </el-button>
          <el-button v-hasPermi="['jihuo:data:remove']" icon="el-icon-delete" size="mini" type="text" @click="handleDelete(scope.row)">
            删除
          </el-button>
          <el-button v-hasPermi="['jihuo:data:query']" icon="el-icon-document" size="mini" type="text" @click="handleInfo(scope.row)">
            详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :limit.sync="queryParams.pageSize" :page.sync="queryParams.pageNum" :total="total" @pagination="getList"/>

    <!-- 添加或修改数据包对话框 -->
    <el-dialog :title="title" :visible.sync="open" append-to-body width="600px">
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <el-form-item label="数据包名称" prop="jhDataName">
          <el-input v-model="form.jhDataName" placeholder="请输入数据包名称"/>
        </el-form-item>
        <el-form-item label="货品链接" prop="jhUrl">
          <el-input v-model="form.jhUrl"  type="textarea" :rows="4" placeholder="请输入货品链接，多个链接间请用换行分割"/>
        </el-form-item>
        <el-form-item label="备注" prop="jhRemark">
          <el-input v-model="form.jhRemark" placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-if="showConfirmButton">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导入数据包对话框 -->
    <el-dialog
      :title="data.title"
      :visible.sync="data.open"
      width="400px"
    >
      <el-upload ref="upload" :limit="1" accept=".txt" :headers="data.uploadHeaders" :action="data.uploadUrl" :disabled="data.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入txt格式文件。</span>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="data.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 失败URL列表对话框 -->
    <el-dialog title="解析失败的URL列表" :visible.sync="failDialogVisible" width="70%">
      <el-table :data="failUrls" border>
        <el-table-column prop="url" label="URL" show-overflow-tooltip>
          <template slot-scope="scope">
            <a :href="scope.row.url" target="_blank">{{ scope.row.url }}</a>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="copyAllUrls(failUrls)">一键复制</el-button>
        <el-button @click="failDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>
    <!-- 成功URL列表对话框 -->
    <el-dialog title="解析成功的URL列表" :visible.sync="successDialogVisible" width="70%">
      <el-table :data="successUrls" border>
        <el-table-column prop="url" label="URL" show-overflow-tooltip>
          <template slot-scope="scope">
            <a :href="scope.row.url" target="_blank">{{ scope.row.url }}</a>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="copyAllUrls(successUrls)">一键复制</el-button>
        <el-button @click="successDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {addData, delData, getData, listData, updateData} from "@/api/jihuo/data";
import { getToken } from "@/utils/auth";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { Splitpanes, Pane } from "splitpanes";
import "splitpanes/dist/splitpanes.css";

export default {
  name: "Data",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 数据包表格数据
      dataList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        jhDataName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      //数据包导入
      data : {
        //是否显示弹出层
        open: false,
        //上传的地址
        uploadUrl: process.env.VUE_APP_BASE_API + '/jihuo/data/import',
        //设置请求头
        uploadHeaders: {
          Authorization: "Bearer " + getToken()
        },
        title: '数据包导入',
        // 是否禁用上传
        isUploading: false,
      },
      //新增/修改/详情 对话框是否显示确定按钮
      showConfirmButton: true,
      // 失败URL对话框
      failDialogVisible: false,
      failUrls: [],
      successDialogVisible: false,
      successUrls: [],
      currentRow: null,
      // 分页相关
      urlPagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 复制所有URL */
    copyAllUrls(urls) {
      const text = urls.map(item => item.url).join('\n');
      navigator.clipboard.writeText(text).then(() => {
        this.$message.success('复制成功');
      }).catch(err => {
        this.$message.error('复制失败: ' + err);
      });
    },

    /** 查询数据包列表 */
    getList() {
      this.loading = true;
      listData(this.queryParams).then(response => {
        this.dataList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        jhId: null,
        jhRevision: null,
        jhCreatedBy: null,
        jhCreatedTime: null,
        jhUpdatedBy: null,
        jhUpdatedTime: null,
        jhDataName: null,
        jhNum: null,
        jhDeleted: null,
        jhUrl: '',
        jhUrls: null,
        jhRemark: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.jhId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.showConfirmButton = true;
      this.reset();
      this.open = true;
      this.title = "添加数据包";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.showConfirmButton = true;
      this.reset();
      const jhId = row.jhId || this.ids
      getData(jhId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改数据包";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 将多行文本解析为数组
          if (this.form.jhUrl) {
            this.form.jhUrls = this.form.jhUrl.split('\n').map(url => url.trim()).filter(url => url);
          } else {
            this.form.jhUrls = [];
          }
          if (this.form.jhId != null) {
            updateData(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addData(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const jhIds = row.jhId || this.ids;
      this.$modal.confirm('是否确认删除数据包编号为"' + jhIds + '"的数据项？').then(function () {
        return delData(jhIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 详情按钮操作 */
    handleInfo(row){
      this.showConfirmButton = false;
      this.reset();
      const jhId = row.jhId || this.ids
      getData(jhId).then(response => {
        this.form = response.data;
        this.form.jhUrl = response.data.jhUrls.join('\n');
        this.open = true;
        this.title = "数据包详情";
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('jihuo/data/export', {
        ...this.queryParams
      }, `data_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleUpload() {
      this.data.open = true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.data.isUploading = true;
      this.data.open = false;
      this.data.isUploading = false;
      this.$message({
        message: '数据导入中，请等待...',
        type: 'warning',
        duration: 1000 // 单位毫秒，可根据需要调整显示时间
      });
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      let { msg } = response;
      let type = 'success';
      if (msg == 1){
        msg = '数据导入成功';
      }else {
        type = 'warning';
      }

      setTimeout(()=>{
        this.$refs.upload.clearFiles();
        this.getList();
        this.$message({
          message: msg,
          type: type,
          duration: 1000 // 单位毫秒，可根据需要调整显示时间
        });
      }, 1000)
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },

    showFailUrls(row) {
      if (row.jhFailUrls && row.jhFailUrls.length > 0) {
        this.failUrls = row.jhFailUrls.map(url => ({ url }));
        this.currentRow = row;
        this.failDialogVisible = true;
      }
    },

    showSuccessUrls(row) {
      if (row.jhSuccessUrls && row.jhSuccessUrls.length > 0) {
        // 转换字符串数组为对象数组
        this.successUrls = row.jhSuccessUrls.map(url => ({ url }));
        this.currentRow = row;
        this.urlPagination.total = this.successUrls.length;
        this.urlPagination.currentPage = 1;
        this.successDialogVisible = true;
      }
    },

    handleSizeChange(val) {
      this.urlPagination.pageSize = val;
      this.urlPagination.currentPage = 1;
    },

    handleCurrentChange(val) {
      this.urlPagination.currentPage = val;
    }
  }
};
</script>
